<?php
namespace plugins\goods\model;
use plugins\goods\model\GoodsSpecListModel;
use think\Db;
use think\Model;
use plugins\order\model\OrderGoodsListModel;
/**
 * 会员模型
 */
class GoodsModel extends Model
{
    //商品主图转换
    public function getGoodsImgAttr($value)
    {
        $goods_img = $value ? zy_domain() . $value : '';
        return $goods_img;
    }
    //商品列表
    public function goodsList()
    {
        $list = $this->all();
        $list = $list->toArray();
        return $list;
    }
    /**
     * 商品详情
     */
    public function goodsDetail(array $where)
    {
        $list = $this->get($where);
        if (!empty($list)) {
            $list = $list->toArray();
            //获取店铺信息
            $store                = Db::name('store')->where('store_id', $list['store_id'])->find();
            $list['store_name']   = $store['store_name'];
            $list['add_time']     = date('Y-m-d H:i:s', $list['add_time']);
            $list['store_logo']   = zy_domain() . '/plugins/store/view/image/' . $store['store_log'];
            $list['store_score']  = 5;
            $list['goods_detail'] = autoHtmlspecialcharsDecode($list['goods_detail']);
            $list['detail_img']   = json_decode($list['detail_img']) ?: [];
            foreach ($list['detail_img'] as $key => $value) {
                $list['detail_img'][$key] = zy_domain() . $value;
            }
        }
        return $list;
    }
    /**
     * 获取搜索记录
     */
    public function getSearchRecord($uid, $search_num = 10)
    {
        try {
            $search = Db::name('goods_search')->where('uid', $uid)->find();
            //去掉开头和结尾的##
            $record = substr($search['search_record'], 2, -2);
            $record = explode("####", $record);
            //去空
            $record= array_filter($record);
            return array_slice($record, 0, $search_num) ?: [];
        } catch (\Exception $e) {
            return [];
        }
    }
    /**
     * 添加搜索记录 + 去重
     */
    public function addSearchRecord($uid = '', $goods_name)
    {
        //如果uid为空不添加搜索记录
        if (empty($uid)) {
            return false;
        }
        try {
            $search = Db::name('goods_search')->where('uid', $uid)->find();
            if (empty($search)) {
                $da = [
                    'uid'           => $uid,
                    'search_record' => "##" . $goods_name . "##",
                ];
                Db::name('goods_search')->insert($da);
            } else {
                //判断前十个是否存在该搜索内
                $search_record = $this->getSearchRecord($uid);
                $str_res = $search['search_record'];
                if (in_array($goods_name, $search_record)) {
                    //删除原来的搜索，增加新的搜索记录
                    $str_res = str_replace( "##" . $goods_name . "##", '', $search['search_record']);
                    $s = [
                        'search_record' => $str_res,
                    ];
                    Db::name('goods_search')->where('uid', $uid)->update($s);
                    // return false; //如果搜索记录中已存在，则不添加
                }
                $da = [
                    'uid'           => $uid,
                    'search_record' => "##" . $goods_name . "##" . $str_res,
                ];
                Db::name('goods_search')->where('uid', $uid)->update($da);
            }
        } catch (\Exception $e) {
            return false;
        }
    }
    /**
     * 查询商品下未完成订单数量
     */
    public function unfinishedOrderNum($gid = [])
    {
        if (empty($gid)) {
            return zy_sys_echo(false, '商品id不能为空', null, -100);
        }
        try {
            //根据商品id查询所有sku
            $sku              = $this->getSkus( $gid );
            $order_goods_list = new OrderGoodsListModel;
            $order_num        = $order_goods_list->where('order_goods_sku', 'in', $sku)->group('order_num')->value('order_num');
            $order            = new \plugins\order\model\OrderModel;
            $order_list       = $order->where('order_num', 'in', $order_num)
                ->where('order_status', 'in', [1, 2, 3])
                ->where('order_refund', 4)
                ->select()->toArray();
        } catch (\Exception $e) {
            $order_list = [];
        }
        $da = [
            'order_count' => 0,
            'order_num'   => [],
        ];
        if (empty($order_list)) {
            return $da;
        }
        $da['order_count'] = count($order_list);
        $da['order_num']   = array_column($order_list, 'order_num');
        return $da;
    }
    /**
     * 获取销量和库存信息
     */
    public function getSellinventory( $gid )
    {
        $goods = $this->where('id', $gid)->find();
        $sell_num = 0; //总销量
        $inventory = 0; //总库存
        try {
            //根据规格计算销量
            $sku = $this->getSkus( $gid );
            $sell_num = GoodsSpecListModel::where('sku', 'in', $sku)->sum('sale_num');
            $inventory = GoodsSpecListModel::where('sku', 'in', $sku)->sum('num');
        } catch (\Exception $e) {
            $sell_num = $goods['sell_num'];
            $inventory = $goods['inventory'];
        }
        $da = [
            'sell_num' => $sell_num,
            'inventory' => $inventory,
        ];
        return $da;
    }
    /**
     * 根据商品查询sku
     */
    public function getSkus( $gid )
    {
        $sku = GoodsSpecListModel::where('gid', 'in', $gid)->column('sku');
        return $sku;
    }
    /**
     * 获取运费
     */
    public function getFreight( $data )
    {
        $freight = new GoodsFreightModel();
        $freight_id = $data['freight_id'];
        $province = $data['province'];
        $goods_num = $data['goods_num'];
        $store_id = $data['store_id'];
        $res = $freight->getFreight( $freight_id, $province, $goods_num, $store_id);
        return $res;
    }
}
